package com.qys.livesMall.postage.controller.sys;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qys.livesMall.common.result.R;
import com.qys.livesMall.framework.utils.SecurityUtils;
import com.qys.livesMall.postage.model.entity.PostageCountry;
import com.qys.livesMall.postage.model.query.RequestData;
import com.qys.livesMall.postage.service.PostageCountryService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;

/**
 *邮费国家地区
 * @author
 * @since 2023-06-02
 */
@RestController
@RequestMapping("/postageCountry")
public class PostageCountryController {
    @Resource
    private PostageCountryService postageCountryService;

    @PostMapping("/page")
    public R<Page<PostageCountry>> listPage(@RequestBody RequestData<PostageCountry> data){
        Page<PostageCountry> page = data.getPage();
        PostageCountry postageCountry=data.getData();
        PostageCountry newPostageCountry = new PostageCountry();
        BeanUtil.copyProperties(postageCountry,newPostageCountry,CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        LambdaQueryWrapper<PostageCountry> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.setEntity(newPostageCountry);
        return R.ok(postageCountryService.page(page, queryWrapper));
    }

    @GetMapping("/{id}")
    public R<PostageCountry> get(@PathVariable Long id){
        LambdaQueryWrapper<PostageCountry> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PostageCountry::getId,id);
        long count = postageCountryService.count(queryWrapper);
        return count<1?R.fail("没有这条记录"):R.ok(postageCountryService.getById(id));
    }

    @PostMapping("/save")
    public R save(@RequestBody PostageCountry postageCountry){
        String name = SecurityUtils.getUsername();
        PostageCountry newPostageCountry = new PostageCountry();
        BeanUtil.copyProperties(postageCountry,newPostageCountry,CopyOptions.create().setIgnoreNullValue(true).setIgnoreError(true));
        Long id = newPostageCountry.getId();
        if (id != null && id.equals(null)){
            newPostageCountry.setUpdateTime(LocalDateTime.now());
            newPostageCountry.setUpdateBy(name);
        }else {
            newPostageCountry.setCreateTime(LocalDateTime.now());
            newPostageCountry.setUpdateTime(LocalDateTime.now());
            newPostageCountry.setCreateBy(name);
            newPostageCountry.setUpdateBy(name);
        }
        return postageCountryService.saveOrUpdate(newPostageCountry)? R.ok():R.fail("操作失败");
    }
}
